import fs from 'fs-extra';
import path from 'path';

function getArgType(arg){
	return Object.prototype.toString.call(arg).toLowerCase().match(/\s(\w+)/)[1];
}

function simpleTemplate(templ,conf){
	let pars=templ&&templ.match(/{.+?}/g);
	if (pars) {
		pars=pars.map(p=>{return p.replace(/{\s*(\w+).*?}/,'$1')});
		pars.forEach((c,i)=>{
			let reg=new RegExp('{\\s*'+c+'\\s*(?:=\\s*(\\S*?))?\\s*?}','g');
			templ=templ.replace(reg,(a,b)=>{
				return getArgType(conf[c])=='function'?conf[c]():(conf[c]?conf[c]:(b?b:a));
			});
		});
	}
	return templ;
}

function convertHtml(html) {
	const marks = {
		'>':'&gt;',
		'<':'&lt;',
		'&':'&amp;',
		' ':'&nbsp;',
		'"':'&quot;',
		"'":'&acute;'
	}
	const reg = new RegExp('['+Object.keys(marks).join('|')+']', 'gi');
	return typeof html !== 'string' ?
			html :
			html.replace(reg, $0 => marks[$0]);
}

function unicodeToChinese(str, safe) {
	str = !str? null: String(str).replace(/(\\u\w+|&#x.*?;)/gi, (a, b) => eval("'"+ b.replace(/&#x(.*?);/g, "\\u$1") +"'"));
	return safe? convertHtml(str): str;
};

function getVersion(dir){
	let vs = ['1.0.0'];
	try{
		vs = fs.readdirSync(dir).filter(file => fs.statSync(path.join(dir, file)).isDirectory());
	}catch(e){}	
	return vs;
}
export {getArgType,simpleTemplate,convertHtml,unicodeToChinese,getVersion};